package com.dean.service;

import org.jxls.common.Context;
import org.jxls.util.JxlsHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class JxlsService {
    private static final Logger logger = LoggerFactory.getLogger(JxlsService.class);
    // 文件模板地址
    private static final String TEMP_PATH = "/dean/template/";
    // 文件导出地址
    private static final String RES_PATH ="/dean/res/";

    // 静态内部类实现单例模式
    // 懒汉式 jvm 保证线程安全  jvm 保证每个类只加载一次 内部类只有在调用的时候才加载
    private JxlsService(){}

    private static class JxlsServiceHolder{
        private final static JxlsService INSTANCE = new JxlsService();
    }

    public static JxlsService getInstance(){
        return JxlsService.JxlsServiceHolder.INSTANCE;
    }


    /**
     *
     * @param tempName
     * @param context
     */
    public void export(String tempName,Context context){
        String nowTime = DateTimeFormatter.ofPattern("yyyyMMddHHmmss").format(LocalDateTime.now());
        String resName = tempName.replace(".xls",nowTime+".xls").replace(".xlsx",nowTime+".xlsx");
        try(InputStream inputStream = new FileInputStream(TEMP_PATH+tempName);
            OutputStream outputStream = new FileOutputStream(RES_PATH+resName)){
            JxlsHelper.getInstance().setUseFastFormulaProcessor(false).processTemplate(inputStream,outputStream,context);
        } catch (FileNotFoundException e) {
            logger.error("导出excel文件失败，失败原因:{}",e.getMessage(),e);
        } catch (IOException e) {
            logger.error("导出excel文件失败，失败原因:{}",e.getMessage(),e);
        }
        logger.info("文件生成成功,文件导出路径[{}]",RES_PATH+resName);
    }
}
